
import { _decorator, Component, Node, Material, UITransform, Sprite, SpriteFrame, Prefab, v4, ValueType } from 'cc';
import Action3dManager, { ActionMngType } from '../../Script/Common/Action3dManager';
import GameData from '../../Script/Common/GameData';
import GlobalData from '../../Script/Common/GlobalData';
import GlobalPool from '../../Script/Common/GlobalPool';
import Loader from '../../Script/Common/Loader';
import PlayerData from '../../Script/Common/PlayerData';
import yyComponent from '../../Script/Common/yyComponent';
import { EventType } from '../../Script/GameSpecial/GameEventType';
import { GlobalEnum } from '../../Script/GameSpecial/GlobalEnum';
import { LoopListH } from '../LoopListH/LoopListH';
import { RoleNameCfg } from '../../Script/GameSpecial/RoleNameCfg';
const { ccclass, property } = _decorator;

@ccclass('MatchUI')
export class MatchUI extends yyComponent {

    protected initSub() {
        this.initEnemies();
        this.initMap();
        this.initRoleLayer();
    }
    protected resetSub() {
        this.resetEnemies();
        this.resetMap();
        this.resetRoleLayer();
    }

    public show() {
        this.node.active = true;
        this.reset();
        this.addRoleLayer();
        this.startMatch();
        this.randomTargetMap();
    }

    //#region 角色模型
    @property(Node)
    protected roleLayer: Node = null;
    protected initRoleLayer() { }
    protected resetRoleLayer() {
        GlobalPool.putAllChildren(this.roleLayer);
    }
    protected addRoleLayer() {
        let node = GlobalPool.get("ShopRole");
        if (!!node) {
            this.roleLayer.addChild(node);
        } else {
            Loader.loadBundle("Role", () => {
                Loader.loadBundleRes("Role", "Prefab/ShopRole", (res) => {
                    GlobalPool.createPool(res.data.name, res, res.data.name);
                    if (this.node.active && this.roleLayer.children.length == 0) {
                        let role = GlobalPool.get("ShopRole");
                        this.roleLayer.addChild(role);
                    }
                }, Prefab, false);
            }, false, false);
        }
    }
    //#endregion

    //#region 匹配角色
    @property(Node)
    protected enemiesLayer: Node = null;
    @property(SpriteFrame)
    protected emptyImg: SpriteFrame = null;
    protected matchPtr: number = 0;
    protected itemScale: number = 1.2;
    protected enemyMatchFinished: boolean = false;
    protected initEnemies() {
        this.enemyMatchFinished = false;
    }
    protected resetEnemies() {
        let children = this.enemiesLayer.children;
        for (let i = children.length - 1; i >= 0; --i) {
            children[i].getComponent(Sprite).spriteFrame = this.emptyImg;
            children[i].setScale(1, 1, 1);
        }
        this.matchPtr = 0;
        this.enemyMatchFinished = false;
    }
    protected startMatch() {
        this.randomEnemyName(10);
        let data = [];
        for (let i = 0; i < 10; ++i) {
            data.push(this.randomMatchEnemyData());
        }
        GlobalData.set(GlobalEnum.myGlobalDataType.matchEnemies, data);
        this.matchPtr = 0;
        this.enemiesLayer.children[this.matchPtr].setScale(this.itemScale, this.itemScale, this.itemScale);
        this.autoMatch();
    }
    protected autoMatch() {
        setTimeout(this.matchOne.bind(this), 200 + Math.round(Math.random() * 100));
        // this.scheduleOnce(this.matchOne, 0.2 + Math.random() * 0.1);
    }
    protected randomMatchEnemyData() {
        let data: any = {};
        //随机武器
        let weapons = [
            GlobalEnum.WeaponType.captain,
            GlobalEnum.WeaponType.claw,
            GlobalEnum.WeaponType.gun,
            GlobalEnum.WeaponType.hunter,
            GlobalEnum.WeaponType.katana,
            GlobalEnum.WeaponType.knife,
            GlobalEnum.WeaponType.trapper,
        ];
        let index = Math.floor(Math.random() * (weapons.length - 0.001));
        data.weaponType = weapons[index];
        let weaponData = GameData.getData(GlobalEnum.GameDataType.GoodsData).weapon[weapons[index]];
        let num = weaponData.num;
        if (num == 1) {
            data.weaponId = num;
        } else {
            if (Math.random() > 0.9) {
                data.weaponId = num;
            } else {
                data.weaponId = Math.floor(Math.random() * (num - 1.001)) + 1;
            }
        }
        //皮肤
        data.skin = Math.floor(Math.random() * 30.999) + 1;
        // if (Math.random() < 0.9) {
        // } else {
        //     data.skin = Math.floor(Math.random() * 5.99) + 13;
        // }
        //饰品
        let hat = 0;
        if (Math.random() > 0.8) {
            hat = Math.floor(Math.random() * 14.99) + 1;
        }
        data.hat = hat;
        return data;
    }
    //随机角色名字
    protected randomEnemyName(count: number) {
        let arr = [];
        let ids = [];
        //todo:读取角色名字文件，随机选取count个
        for (let i = 0; i < count; ++i) {
            arr.push(RoleNameCfg.getRandomName(ids));
        }
        GlobalData.set(GlobalEnum.myGlobalDataType.matchEnemyNames, arr);
    }
    protected matchOne() {
        this.emit(EventType.Common.AudioEvent.playEffect, GlobalEnum.AudioClip.gold);
        let node = this.enemiesLayer.children[this.matchPtr];
        let data = GlobalData.get(GlobalEnum.myGlobalDataType.matchEnemies);
        Loader.loadBundleRes("UI", "Image/shop/skin/skin" + data[this.matchPtr].skin + "/spriteFrame", (res) => {
            node.getComponent(Sprite).spriteFrame = res;
            let s = 1;
            node.setScale(s, s, s);
            node.active = false;
            node.active = true;
        });
        this.matchPtr++;
        if (this.matchPtr < data.length) {
            let s = this.itemScale;
            this.enemiesLayer.children[this.matchPtr].setScale(s, s, s);
            this.autoMatch();
        } else {
            setTimeout(() => {
                this.onMatchFinish();
            }, 200);
        }
    }
    protected onMatchFinish() {
        // this.emit(EventType.LevelEvent.matchFinish);
        this.enemyMatchFinished = true;
    }
    //#endregion

    //#region 地图
    @property(LoopListH)
    protected loopMap: LoopListH = null;
    protected mapOffset: number = 0;
    protected targetOffset: number = 0;
    protected spaceX: number = 330;
    //地图类型id
    protected mapIds: number[] = [];
    protected mapAnimRate: number = 0;
    protected mapAnimFinished: boolean = false;
    protected initMap() {
        this.mapIds = [1, 8, 2, 3, 9, 4, 5, 8, 6, 7, 8];
        let data = [];
        for (let i = 0, c = this.mapIds.length; i < c; ++i) {
            data.push("map" + this.mapIds[i]);
        }
        this.loopMap.init({ spaceX: this.spaceX, data: data });
        this.mapOffset = 0;
        this.mapAnimFinished = false;
    }
    protected resetMap() {
        this.loopMap.reset();
        this.mapOffset = 0;
        this.mapAnimFinished = false;
    }
    protected randomTargetMap() {
        let lv = PlayerData.getData("gameData.curLevel");
        let mapId;
        let index = lv - 1;
        if (index >= this.mapIds.length) {
            // index = Math.floor(Math.random() * (this.mapIds.length - 0.001));
            index = index % this.mapIds.length;
        }
        mapId = this.mapIds[index];
        let w = this.spaceX * this.mapIds.length;
        this.targetOffset = -w * 1.5 - (index + 1) * this.spaceX + this.spaceX;//10.5: 0.5 + 10
        // GlobalData.set(GlobalEnum.myGlobalDataType.matchMap, mapId);
        let maps = [];
        if (mapId <= 7) {
            maps = [mapId];
        } else if (mapId == 8) {
            let arr = [1, 2, 4, 5];
            for (let i = 0; i < 3; ++i) {
                let ii = Math.floor(Math.random() * 3.99);
                maps.push(arr[ii]);
            }
            maps.push(8);
        } else if (mapId == 9) {
            let arr = [3, 6, 7];
            for (let i = 0; i < 3; ++i) {
                let ii = Math.floor(Math.random() * 2.99);
                maps.push(arr[ii]);
            }
            maps.push(9);
        }
        GlobalData.set(GlobalEnum.myGlobalDataType.matchMap, maps);

        this.mapAnimRate = 0;
        let tween = Action3dManager.tweenTo(2, "mapAnimRate", 1, false);
        tween.easing(Action3dManager.easeInOut(2));
        Action3dManager.getMng(ActionMngType.UI).runAction(this, tween);
    }
    //#endregion

    public update(dt: number) {
        if (!this.mapAnimFinished) {
            // let v = (this.targetOffset - this.mapOffset) * dt;
            // if (Math.abs(v) < 1) {
            //     this.mapOffset = this.targetOffset;
            //     this.mapAnimFinished = true;
            // } else {
            //     this.mapOffset += v;
            // }

            if (this.targetOffset * (1 - this.mapAnimRate) >= -1) {
                this.mapAnimRate = 1;
                this.mapAnimFinished = true;
            }
            let x = this.targetOffset * this.mapAnimRate;
            // if (this.mapAnimRate >= 0.999) {
            //     this.mapAnimFinished = true;
            //     this.mapAnimRate = 1;
            // }
            this.loopMap.setOffset(x);
        } else if (this.enemyMatchFinished) {
            this.enemyMatchFinished = false;
            setTimeout(() => {
                this.emit(EventType.LevelEvent.matchFinish);
            }, 300);
        }
    }

}


